package tech.aistar.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.*;
import tech.aistar.pojo.Order;

import java.math.BigDecimal;
import java.util.List;

public interface OrderMapper {
    @Select("select * from orders")
    List<Order> listAllOrder();

    @Select("select * from orders where id = #{id}")
    Order findOrderById(Integer id);

    @Insert("insert into orders(order_id,user_id,total_amount,address_id,order_status,pay_time,send_time,finish_time,create_time) values (#{orderId},#{userId},#{totalAmount},#{addressId},#{orderStatus},#{payTime},#{sendTime},#{finishTime},#{createTime})")
    int addOrder(Order order);

    int updateOrder(Order order);


    @Delete("delete from orders where orders.order_id=#{OrderId}")
    int deleteOrderById(String OrderId);
    // 查询订单列表（关联用户表获取买家信息，从order_id解析卖家信息）
    @Select("""
        <script>
        SELECT o.*, u.username as buyer_name,
               SUBSTRING_INDEX(o.order_id, '-', -1) as seller_id
        FROM orders o 
        LEFT JOIN user u ON o.user_id = u.id 
        WHERE 1=1
        <if test='orderId != null and orderId != \"\"'>
            AND o.order_id LIKE CONCAT('%', #{orderId}, '%')
        </if>
        <if test='buyerName != null and buyerName != \"\"'>
            AND u.username LIKE CONCAT('%', #{buyerName}, '%')
        </if>
        <if test='orderStatus != null'>
            AND o.order_status = #{orderStatus}
        </if>
        ORDER BY o.create_time DESC
        LIMIT #{offset}, #{size}
        </script>
    """)
    List<Order> selectOrderList(@Param("orderId") String orderId,
                                @Param("buyerName") String buyerName,
                                @Param("orderStatus") Integer orderStatus,
                                @Param("offset") Integer offset,
                                @Param("size") Integer size);

    // 查询订单总数
    @Select("""
        <script>
        SELECT COUNT(*) 
        FROM orders o 
        LEFT JOIN user u ON o.user_id = u.id 
        WHERE 1=1
        <if test='orderId != null and orderId != \"\"'>
            AND o.order_id LIKE CONCAT('%', #{orderId}, '%')
        </if>
        <if test='buyerName != null and buyerName != \"\"'>
            AND u.username LIKE CONCAT('%', #{buyerName}, '%')
        </if>
        <if test='orderStatus != null'>
            AND o.order_status = #{orderStatus}
        </if>
        </script>
    """)
    Long countOrders(@Param("orderId") String orderId,
                     @Param("buyerName") String buyerName,
                     @Param("orderStatus") Integer orderStatus);

    // 根据订单ID获取订单详情
    @Select("SELECT o.*, u.username as buyer_name, SUBSTRING_INDEX(o.order_id, '-', -1) as seller_id FROM orders o LEFT JOIN user u ON o.user_id = u.id WHERE o.order_id = #{orderId}")
    Order findByOrderId(String orderId);

    // 更新订单状态
    @Update("UPDATE orders SET order_status = #{orderStatus} WHERE order_id = #{orderId}")
    int updateOrderStatus(@Param("orderId") String orderId, @Param("orderStatus") Integer orderStatus);

    // 取消订单并退款（更新订单状态和用户余额）
    @Update("UPDATE orders SET order_status = 4 WHERE order_id = #{orderId}")
    int cancelOrder(String orderId);

    // 更新用户余额（退款给买家）
    @Update("UPDATE user SET money = money + #{amount} WHERE id = #{userId}")
    int refundToUser(@Param("userId") Integer userId, @Param("amount") BigDecimal amount);

    // 获取用户当前余额
    @Select("SELECT money FROM user WHERE id = #{userId}")
    BigDecimal getUserMoney(Integer userId);

    // 完成订单并自动打款给卖家（从order_id解析卖家ID）
    @Update("UPDATE orders SET order_status = 3, finish_time = NOW() WHERE order_id = #{orderId}")
    int completeOrder(String orderId);

    // 打款给卖家
    @Update("UPDATE user SET money = money + #{amount} WHERE id = #{userId}")
    int payToSeller(@Param("userId") Integer userId, @Param("amount") BigDecimal amount);
}
